package hv.fmw.core.assets {
	import hv.fmw.core.command.CommandEvent;
	import hv.fmw.core.command.ParallelCommand;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	public class AssetsManager extends EventDispatcher {
		
		private static var _instance:AssetsManager;
		private var _assets:Dictionary = new Dictionary();
		private var _loaded:Boolean = false;
		
		public function  AssetsManager(enforcer:SingletonEnforcer){
			
		}
		
		public static function getInstance(): AssetsManager{
			if(_instance == null)_instance = new  AssetsManager(new SingletonEnforcer());
			return _instance;
		}

		public function add(node:XMLList) : void {
			var l:int = node.length();
			var queue:ParallelCommand = new ParallelCommand();
			var asset:XML;
			for(var i:int=0; i<l; i++){
				asset = node[i];
				queue.addCommand(new AssetLoaderCmd(asset.@id, asset.@src));
				_assets[String(asset.@id)] = new AssetVo(asset.@id, asset.@src);
			}
			queue.addEventListener(CommandEvent.ALL_COMMAND_COMPLETE, _onLoadAssetsComplete);
			queue.addEventListener(CommandEvent.COMMAND_COMPLETE, _onLoadEachAssetHandler);
			queue.execute();
		}
		
		/*
		 * Populates assets dictionary when asset is loaded
		 */
		private function _onLoadEachAssetHandler(event : CommandEvent) : void {
			var command:AssetLoaderCmd = event.command as AssetLoaderCmd;
			var asset:AssetVo = _assets[command.id];
				asset.pushContent(command.content);
		}
		
		/*
		 * When all assets from config are loaded
		 */
		private function _onLoadAssetsComplete(event : CommandEvent) : void {
			_loaded = true;
			dispatchEvent(new Event(Event.COMPLETE));
		}

		public function getAsset(id:String) : AssetVo {
			return _assets[id];
		}

		public function get loaded() : Boolean {
			return _loaded;
		}
	}
}

internal class SingletonEnforcer{}